import React from 'react'
import { Button } from 'antd'
import Table from '../../../components/Table'
import { connect } from 'react-redux'
import _ from 'lodash'
import Immutable from 'immutable'
import PubSub from 'pubsub-js'
import { GET_DETAIL } from '../constant'
import { setBookInfo } from '../../action/action'
import './index.less'

class BookInfo extends React.PureComponent {
  columns = [
    {
      title: 'id',
      dataIndex: 'bookId',
      key: 'bookId',
      align: 'center'
    },
    {
      title: '书名',
      dataIndex: 'name',
      key: 'name',
      search: true
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
      search: true
    },
    {
      title: '条码号',
      dataIndex: 'isbn',
      key: 'isbn',
      search: true,
      align: 'center'
    },
    {
      title: '定位',
      dataIndex: 'pressmark',
      key: 'pressmark',
      search: true,
      align: 'center'
    },
    {
      title: '',
      dataIndex: 'accLevel',
      key: 'accLevel',
      align: 'center',
      render: (text, record) => {
        return (<Button onClick={() => this.onDetail(text, record)}>详情</Button>)
      }
    },
  ]

  constructor (props) {
    super(props)
    this.state = {
      tableData: Immutable.fromJS([])
    }
  }

  onDetail = (text, record) => {
    const { dispatch } = this.props
    dispatch(setBookInfo(record.bookId))
    PubSub.publish(GET_DETAIL)
  }

  getSelectData = (selectedRowKeys) => {

  }

  static getDerivedStateFromProps (nextProps, prevState) {
    const nextState = {}
    const { tableData } = nextProps
    if (!Immutable.is(tableData, prevState.tableData)) {
      nextState.tableData = tableData
    }
    if (!_.isEmpty(nextState)) {
      return nextState
    }
    return null
  }

  render () {
    const { tableData } = this.state
    const { height } = this.props
    return (
      <Table
        rowKey={'bookId'}
        columns={this.columns}
        scroll={{ y: height ? height - 90 : '' }}
        dataSource={tableData.toJS()}
        className={'table-height'}
        pagination={{
          showTotal: (total, range) => `第${range[0]}-${range[1]}条/共${total}条`,
          defaultPageSize: 10,
          showSizeChanger: true,
          pageSizeOptions: [10, 20, 50, 100, 200, 500],
        }}
      />
    )
  }
}

const mapStateToProps = (state) => {
  return {
    tableData: state.get('getBookInfoTableData'),
    height: state.get('getHeight')
  }
}
export default connect(mapStateToProps)(BookInfo)